package com.tn.exam.action.base;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class BaseAction extends ActionSupport {
	public Logger log = LoggerFactory.getLogger(getClass());
	private static final long serialVersionUID = 1L;
	
	protected void sendString(String jsonString) {
		try {
			log.debug(jsonString);
			HttpServletResponse response = this.getHttpResponse();
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(jsonString);
		} catch (IOException e) {
			log.error("发送字符串失败!", e);
		}
	}


	protected String toJSON(Object o) {
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			return objectMapper.writeValueAsString(o);
		} catch (Exception e) {
			return "";
		}
	}
	
	protected HttpServletResponse getHttpResponse(){
		return ServletActionContext.getResponse();
	}
	
	protected HttpServletRequest getHttpRequest(){
		return ServletActionContext.getRequest();
	}
	
	protected HttpSession getHttpSession(){
		return ServletActionContext.getRequest().getSession();
	}
	
	protected ServletContext getServletContext(){
		return ServletActionContext.getServletContext();
	}
	
	protected ActionContext getActionContext(){
		return ServletActionContext.getActionContext(this.getHttpRequest());
	}
	
}
